/**
 * JAVACC DEMO 1.0
 * @copy right dwusoft company All rights reserved. 
 * @Package com.apache.bid.service.plugins  
 */
package com.apache.bid.service.plugins;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.beans.BeanUtils;

import com.apache.api.manager.PluginConnector;
import com.apache.api.vo.ParamsVo;
import com.apache.bid.common.BidCommonUtil;
import com.apache.bid.common.Constant;
import com.apache.bid.common.TeaUtil;
import com.apache.bid.common.cache.BidCacheFactory;
import com.apache.bid.common.cache.BidCacheManager;
import com.apache.bid.entity.BidApply;
import com.apache.bid.entity.BidApplyHistory;
import com.apache.bid.entity.BidItem;
import com.apache.bid.entity.BidItemHistory;
import com.apache.bid.entity.BidItemPrice;
import com.apache.bid.manager.BidApplyHistoryManager;
import com.apache.bid.manager.BidApplyManager;
import com.apache.bid.manager.BidItemHistoryManager;
import com.apache.bid.manager.BidItemManager;
import com.apache.bid.manager.BidItemPriceManager;
import com.apache.cache.util.Validator;
import com.apache.tools.DateUtils;
import com.apache.tools.DateUtils.FmtStr;
import com.apache.tools.NumberUtils;

/**
 * description:  将完成的标的移动到历史表插件
 * @author Hou Dayu 创建时间：2016-3-29  
 * 
 */
public class RemoveItemHistoryPluginImpl implements PluginConnector {

	private BidItemManager bidItemManager;
	private BidItemPriceManager bidItemPriceManager;
	private BidItemHistoryManager bidItemHistoryManager;
	private BidApplyManager bidApplyManager;
	private BidApplyHistoryManager bidApplyHistoryManager;

	/**
	 * TODO 简单描述该方法的实现功能（可选）.  
	 * @see com.zbxsoft.api.manager.PluginConnector#execute(com.zbxsoft.api.vo.ParamsVo)  
	 */
	public Object execute(ParamsVo param) throws Exception {
		BidItem item = (BidItem) param.getObj();
		if (Validator.isEmpty(item))
			return false;
		BidItemHistory histoy = new BidItemHistory();
		histoy.addItemInfo(item);
		ParamsVo vo = new ParamsVo();
		vo.setInfoId(item.getItemId());
		BidItemPrice price = (BidItemPrice) bidItemPriceManager.getInfoById(vo);
		String bidTime = DateUtils.Now.fmt_yyyyMMdd_HHmmss();
		long nowTime = BidCommonUtil.getMillTime(bidTime, "yyyy-MM-dd HH:mm:ss");
		long closeTime = BidCommonUtil.getMillTime(price.getCloseTime(), "yyyy-MM-dd HH:mm:ss");
		long czTime = 5 * 60 * 1000;
		if ((nowTime - closeTime) < czTime)
			return false;
		histoy.addItemPrice(price);
		long opentime = BidCommonUtil.getMillTime(price.getOpenTime(), FmtStr.yyyyMMdd_HHmmss.toString());
		long closetime = BidCommonUtil.getMillTime(price.getFirstBidTime(), FmtStr.yyyyMMdd_HHmmss.toString());
		histoy.setTakeTime(String.valueOf((closetime - opentime) / 1000));
		histoy.setItemStatus("1");//未交割
		if (Constant.BIDMODE_FEJJZX.equals(item.getBidMode()) || Constant.BIDMODE_FEJJFX.equals(item.getBidMode())) {
			histoy.setMsgStatus("2");//已通知
		} else {
			histoy.setMsgStatus("1");//未通知
			BigDecimal fistrValue = new BigDecimal(Validator.getDefaultStr(price.getFirstValue(), "0"));

			BigDecimal lastValue = new BigDecimal(0);
			if (isNumeric(Validator.getDefaultStr(price.getLastValue(), "0"))) {
				lastValue = new BigDecimal(Validator.getDefaultStr(price.getLastValue(), "0"));
			} else {
				String lastValueStr = TeaUtil.decryptByTea(price.getLastValue());
				lastValue = new BigDecimal(lastValueStr);
			}
			if (lastValue.compareTo(new BigDecimal(0)) > 0) {
				double overPrice = NumberUtils.subtract(lastValue.doubleValue(), fistrValue.doubleValue());
				histoy.setOverPrice(String.valueOf(overPrice));
				histoy.setYjl(String.valueOf(NumberUtils.divide(overPrice, fistrValue.doubleValue(), 2)));
				histoy.setLastValue(lastValue.toString());
			} else {
				histoy.setOverPrice("0");
				histoy.setYjl("0");
			}
		}
		ParamsVo<BidItemHistory> itemHistory = new ParamsVo<BidItemHistory>();
		histoy.setItemStatus(Constant.getInstance().getItemConfig("statusStop"));
		itemHistory.setObj(histoy);
		String itemId = bidItemHistoryManager.saveInfo(itemHistory);
		if (Validator.isNull(itemId))
			return false;
		bidItemPriceManager.deleteInfo(vo);
		boolean delMark = bidItemManager.deleteInfo(vo);
		if (delMark) {
			if (Constant.SETYPE_HD.equals(item.getSessionType())) {
				saveApplys(item.getItemId());
			}
			BidCacheFactory.getInstance().getCacheManager("item")
					.removeCacheObject(BidCacheManager.item_prefix + item.getItemId());
		}
		vo = null;
		return true;
	}

	/**
	 * description:  批量移申请记录
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void saveApplys(String itemId) {
		ParamsVo vo = new ParamsVo();
		BidApply apply = new BidApply();
		apply.setItemId(itemId);
		vo.setObj(apply);
		List<BidApply> list = bidApplyManager.getList(vo);
		if (!Validator.isEmpty(list)) {
			List<BidApplyHistory> apps = new ArrayList<BidApplyHistory>();
			for (BidApply ay : list) {
				BidApplyHistory bah = new BidApplyHistory();
				BeanUtils.copyProperties(ay, bah);
				apps.add(bah);
			}
			vo.setObj(null);
			vo.setObjs(apps);
			bidApplyHistoryManager.saveInfo(vo);
			vo.setObj(apply);
			vo.setObjs(null);
			bidApplyManager.deleteInfo(vo);
		}
	}

	private boolean isNumeric(String str) {
		Pattern pattern = Pattern.compile("[0-9]*");
		Matcher isNum = pattern.matcher(str);
		if (!isNum.matches()) {
			return false;
		}
		return true;
	}

	public void setBidItemManager(BidItemManager bidItemManager) {
		this.bidItemManager = bidItemManager;
	}

	public void setBidItemPriceManager(BidItemPriceManager bidItemPriceManager) {
		this.bidItemPriceManager = bidItemPriceManager;
	}

	public void setBidItemHistoryManager(BidItemHistoryManager bidItemHistoryManager) {
		this.bidItemHistoryManager = bidItemHistoryManager;
	}

	public void setBidApplyManager(BidApplyManager bidApplyManager) {
		this.bidApplyManager = bidApplyManager;
	}

	public void setBidApplyHistoryManager(BidApplyHistoryManager bidApplyHistoryManager) {
		this.bidApplyHistoryManager = bidApplyHistoryManager;
	}

}
